package cn.edu.heuet.bnve.fragment;

import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Build;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.xuexiang.xui.widget.layout.ExpandableLayout;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.edu.heuet.bnve.MainActivity;
import cn.edu.heuet.bnve.model.NEUClass;
import cn.edu.heuet.bnve.R;
import cn.edu.heuet.bnve.activity.SettingActivity.TableSettingActivity;
import cn.edu.heuet.bnve.adapter.WeekAdapter;
import cn.edu.heuet.bnve.base.fragment.BaseFragment;
import cn.edu.heuet.bnve.database.ClassDao;
import cn.edu.heuet.bnve.databinding.FragmentTableBinding;
import cn.edu.heuet.bnve.utils.SharepreferencesUtilSystemSettings;
import cn.edu.heuet.bnve.view.TimeTableView;

public class TableFragment extends BaseFragment {

    private ClassDao classDao;
    FragmentTableBinding binding;
    private ExpandableLayout expandableLayout ;
    private List<NEUClass> currentWeekClasses;
    private RecyclerView weekSelectView;
    private int currentWeek=1;
    private TextView weekTitle;
    private TimeTableView timeTableView;
    private Date startDate;
    private int flag=0;
    private WeekAdapter adapter;



    public static TableFragment newInstance() {
        return new TableFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_table;
    }


    @Override
    protected void initView() {
        binding= DataBindingUtil.bind(mRootView);
        expandableLayout = binding.expandableLayout;
        weekTitle = binding.tvWeekNow;
//        weekTitle.getPaint().setFakeBoldText(true);
        weekSelectView = binding.weekSelsectView;
        //设置为线性布局
        weekSelectView.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.HORIZONTAL,false));
        timeTableView = binding.timeTable;

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void initData() {
        /*
        获得当前周数
         */
        loadCurrentWeek();
        weekTitle.setText("第 "+currentWeek+" 周");
        classDao = new ClassDao(mContext);
        // 创建一些假数据
        NEUClass class1 = new NEUClass(1, "Java编程", "计算机楼101", 1, "张老师", 1);
        NEUClass class2 = new NEUClass(2, "数据结构", "计算机楼102", 2, "李老师", 1);
        NEUClass class3 = new NEUClass(3, "算法设计", "数学楼201", 3, "王老师", 2);
        NEUClass class4 = new NEUClass(4, "操作系统", "计算机楼103", 4, "赵老师", 3);
        NEUClass class5 = new NEUClass(5, "计算机网络", "网络楼301", 5, "孙老师", 4);

        // 将数据插入数据库
        classDao.insertClass(class1);
        classDao.insertClass(class2);
        classDao.insertClass(class3);
        classDao.insertClass(class4);
        classDao.insertClass(class5);

        // 输出操作成功提示
        System.out.println("课程数据已插入数据库！");

        adapter = new WeekAdapter(mContext);
        weekSelectView.setAdapter(adapter);
        loadTable();
    }

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void initEvent() {

        binding.ivMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getActivity() instanceof MainActivity) {
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.drawerLayout.openDrawer(Gravity.LEFT);
                }
            }
        });

        weekTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.ivSelectWeek.callOnClick();
            }
        });

        binding.ivSelectWeek.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (expandableLayout.isExpanded()){
                    expandableLayout.collapse();
                    ObjectAnimator rotation = ObjectAnimator.ofFloat(binding.ivSelectWeek, "rotation", 0f, 360f).setDuration(600);
                    rotation.start();
                }
                else {
                    expandableLayout.expand();
                    ObjectAnimator rotation = ObjectAnimator.ofFloat(binding.ivSelectWeek, "rotation", 0f, 180f).setDuration(600);
                    rotation.start();
                }
            }
        });

        binding.ivSettingTable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TableSettingActivity.show(mContext);
            }
        });

        adapter.setOnItemClickLitener(new WeekAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
//                Toast.makeText(mContext, adapter.getmDatas().get(position), Toast.LENGTH_SHORT).show();
                adapter.setThisPosition(position);
                currentWeek = position+1;
                weekTitle.setText("第 "+currentWeek+" 周");
                currentWeekClasses =  classDao.getAll(currentWeek);
                timeTableView.loadData(currentWeekClasses);
            }
        });
//        binding.SRlay.setRefreshHeader(new MaterialHeader(mContext).setShowBezierWave(true));
//        binding.SRlay.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(RefreshLayout refreshlayout) {
//                binding.SRlay.finishRefresh(2000);
//            }
//        });
//        mRootView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                int currentY = 0;
//                switch (motionEvent.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        currentY = (int) motionEvent.getY();
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        int i = (int) motionEvent.getY() - currentY;
//                        if(i > 30){
//                            expandableLayout.expand();
//                            ObjectAnimator rotation = ObjectAnimator.ofFloat(binding.ivSelectWeek, "rotation", 0f, 180f).setDuration(600);
//                            rotation.start();
//                        }else if(i < -30){
//                            expandableLayout.collapse();
//                            ObjectAnimator rotation = ObjectAnimator.ofFloat(binding.ivSelectWeek, "rotation", 0f, 360f).setDuration(600);
//                            rotation.start();
//                        }
//                        break;
//                }
//                return true;
//            }
//        });
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onStart() {
        super.onStart();
        //第一次打开界面
        if(flag==0){
            flag+=1;
        }
        else{
            int copy = currentWeek;
            loadCurrentWeek();
            if (currentWeek!=copy){
                weekTitle.setText("第 "+currentWeek+" 周");
                loadTable();
            }
        }
    }

    /**
     * 计算当前周次
     * @param date
     * @return
     */
    private int calcWeek(Date date) {
        long a=(new Date().getTime() - date.getTime()) / (1000 * 3600 * 24 * 7) + 1;
        return (int)a;
    }

    /**
     * 重新加载
     */
    private void loadCurrentWeek(){
        String time = SharepreferencesUtilSystemSettings.getValue(mContext,"table_start_date",null);
        if(time!=null) {
            try {
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
                Date date = ft.parse(time);
                currentWeek = calcWeek(date);
                if(currentWeek<=0){
                    currentWeek=1;
                }
                if(currentWeek>19){
                    currentWeek=19;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void loadTable(){
        currentWeekClasses = classDao.getAll(currentWeek);
        adapter.setThisPosition(currentWeek-1);
        weekSelectView.scrollToPosition(currentWeek-3);
        timeTableView.loadData(currentWeekClasses);
    }


}